<template>
  <div class="bg-white shadow-md p-4">
    <Navigation :homeRoute="homeRoute" :currentPage="currentPage" />
  </div>
  <div class="container">
    <el-row :gutter="20">
      <!-- 左侧区域：医生门诊 & 处方列表 -->
      <el-col :span="12">
        <div class="left-section">
          <h2 class="title">医生门诊</h2>
          <p class="subtext">当前时间：{{ currentTime }}</p>

          <!-- 处方列表 -->
          <div v-if="isLoading" class="mt-4 text-center">
            <el-spinner></el-spinner>
          </div>

          <el-table
            v-else
            :data="prescriptions"
            stripe
            border
            size="small"
            class="mt-4"
            v-show="prescriptions.length > 0"
          >
            <!-- 自定义序号列（从0开始） -->
            <el-table-column label="序号" width="50">
              <template #default="scope">
                {{ scope.$index }}
              </template>
            </el-table-column>
            
            <el-table-column label="患者姓名" prop="patient.real_name"></el-table-column>
            <el-table-column label="就诊状态" width="120">
              <template #default="scope">
                <el-tag
                  :type="scope.row.status === 1 ? 'success' : 'warning'"
                  :effect="scope.row.status === 1 ? 'dark' : 'light'"
                >
                  {{ scope.row.status === 1 ? '已就诊' : '未就诊' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="接诊医生" prop="doctor.real_name"></el-table-column>
          </el-table>

          <!-- 无数据提示 -->
          <div v-if="prescriptions.length === 0" class="mt-4 text-center text-gray-500">
            <el-empty description="暂无就诊记录"></el-empty>
          </div>
        </div>
      </el-col>

      <!-- 右侧区域：处方添加表单 -->
      <el-col :span="12">
        <div class="right-section">
          <el-card shadow="always">
            <template #header>
              <h3 class="form-title">新增门诊信息</h3>
            </template>

            <el-form 
              :model="prescriptionForm" 
              label-width="120px" 
              ref="formRef"
              :rules="formRules"
              status-icon
            >
              <!-- 处方ID -->
              <el-form-item 
                label="处方ID" 
                prop="prescription_id"
                :rules="{ required: true, message: '请输入处方ID', type: 'number' }"
              >
                <el-input 
                  v-model.number="prescriptionForm.prescription_id" 
                  placeholder="请输入处方ID"
                  type="number"
                ></el-input>
              </el-form-item>

              <!-- 患者ID -->
              <el-form-item 
                label="患者ID" 
                prop="patient_id"
                :rules="{ required: true, message: '请输入患者ID', type: 'number' }"
              >
                <el-input 
                  v-model.number="prescriptionForm.patient_id" 
                  placeholder="请输入患者ID"
                  type="number"
                ></el-input>
              </el-form-item>

              <!-- 医生ID -->
              <el-form-item 
                label="医生ID" 
                prop="doctor_id"
                :rules="{ required: true, message: '请输入医生ID', type: 'number' }"
              >
                <el-input 
                  v-model.number="prescriptionForm.doctor_id" 
                  placeholder="请输入医生ID"
                  type="number"
                ></el-input>
              </el-form-item>

             <el-form-item 
  label="创建时间" 
  prop="create_time"
  :rules="[
    { required: true, message: '请输入创建时间', trigger: 'blur' }
  ]"
>
  <el-input
    v-model="prescriptionForm.create_time"
    placeholder="请输入日期 (格式: yyyy-MM-dd)"
    @blur="formatDate($event)"
  ></el-input>
</el-form-item>

              <!-- 就诊类型 -->
              <el-form-item label="就诊类型" prop="type">
                <el-radio-group v-model="prescriptionForm.type">
                  <el-radio :value="1" label="初诊"></el-radio>
                  <el-radio :value="0" label="末诊"></el-radio>
                </el-radio-group>
              </el-form-item>

              <!-- 就诊状态 -->
              <el-form-item label="就诊状态" prop="status">
                <el-radio-group v-model="prescriptionForm.status">
                  <el-radio :value="0" label="未就诊"></el-radio>
                  <el-radio :value="1" label="已就诊"></el-radio>
                </el-radio-group>
              </el-form-item>

              <!-- 操作按钮 -->
              <el-form-item class="button-group">
                <el-button 
                  type="primary" 
                  @click="submitForm"
                  :loading="formLoading"
                >
                  {{ formLoading ? '提交中...' : '添加' }}
                </el-button>
                <el-button @click="resetForm">重置</el-button>
              </el-form-item>
            </el-form>
          </el-card>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage, ElEmpty } from 'element-plus';
import axios from 'axios';
import Navigation from '@/components/Navigation.vue';


const currentPage = '医生门诊';
// 自定义日期格式化函数（使用原生 Date 对象）
const dateFormat = computed(() => {
  return (date) => {
    if (!date) return '';
    const d = new Date(date);
    return [
      d.getFullYear(),
      String(d.getMonth() + 1).padStart(2, '0'),
      String(d.getDate()).padStart(2, '0')
    ].join('-') + ' ' + [
      String(d.getHours()).padStart(2, '0'),
      String(d.getMinutes()).padStart(2, '0'),
      String(d.getSeconds()).padStart(2, '0')
    ].join(':');
  };
});

// 处理日期变化，确保值为有效时间戳
const handleDateChange = (val) => {
  if (val && typeof val === 'number' && !isNaN(val)) {
    // 值有效，无需处理
  } else if (val) {
    // 尝试转换为时间戳
    prescriptionForm.create_time = new Date(val).getTime();
  } else {
    // 值为空，设为 null
    prescriptionForm.create_time = null;
  }
};



// 左侧处方数据
const prescriptions = ref([]);
const isLoading = ref(false); // 数据加载状态

// 右侧表单数据
const prescriptionForm = reactive({
  prescription_id: null,
  patient_id: null,
  doctor_id: null,
  create_time: null,
  type: 1, // 默认初诊
  status: 0 // 默认未就诊
});

// 表单加载状态（避免与数据加载状态冲突）
const formLoading = ref(false);

// 表单验证规则
const formRules = computed(() => ({
  prescription_id: [
    { required: true, message: '请输入处方ID', trigger: 'blur' },
    { type: 'number', message: '请输入有效数字', trigger: 'blur' }
  ],
  patient_id: [
    { required: true, message: '请输入患者ID', trigger: 'blur' },
    { type: 'number', message: '请输入有效数字', trigger: 'blur' }
  ],
  doctor_id: [
    { required: true, message: '请输入医生ID', trigger: 'blur' },
    { type: 'number', message: '请输入有效数字', trigger: 'blur' }
  ],
  create_time: [
    { required: true, message: '请选择创建时间', trigger: 'change' }
  ]
}));

// 表单引用
const formRef = ref(null);

// 当前时间
const currentTime = computed(() => new Date().toLocaleString());

// 页面加载时获取处方数据
onMounted(() => {
  fetchPrescriptions();
});

// 获取处方数据的函数
const fetchPrescriptions = async () => {
  isLoading.value = true;
  try {
    // 使用真实API请求
    const response = await axios.get('/prescription/findAll');
    
    if (response.data && Array.isArray(response.data)) {
      prescriptions.value = response.data;
      console.log('获取处方数据成功:', prescriptions.value);
    } else {
      ElMessage.warning('获取处方数据失败：返回格式不正确');
      console.error('获取处方数据失败，返回数据:', response.data);
    }
  } catch (error) {
    console.error('获取处方数据失败:', error);
    ElMessage.error('系统错误，请重试');
  } finally {
    isLoading.value = false;
  }
};

// 提交表单
const submitForm = async () => {
  formLoading.value = true;
  try {
    await formRef.value.validate();
    
    // 准备表单数据
    const formData = {
      ...prescriptionForm,
      create_time: prescriptionForm.create_time // 时间戳格式
    };
    
    // 发送添加请求
    const response = await axios.post('/prescription/add', formData);
    
    if (response.data === '添加成功') {
      ElMessage.success('处方添加成功');
      resetForm();
      // 重新加载数据
      fetchPrescriptions();
    } else {
      ElMessage.error('处方添加失败：' + (response.data.message || '未知错误'));
    }
  } catch (error) {
    console.error('添加处方失败:', error);
    ElMessage.error('系统错误，请联系管理员');
  } finally {
    formLoading.value = false;
  }
};

// 重置表单
const resetForm = () => {
  formRef.value.resetFields();
  prescriptionForm.type = 1;
  prescriptionForm.status = 0;
};
</script>

<style scoped>
.container {
  padding: 24px;
  min-height: 100vh;
  background-color: #f5f7fa;
}

.left-section {
  background-color: white;
  border-radius: 8px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
}

.title {
  font-size: 20px;
  font-weight: 600;
  color: #1a73e8;
  margin-bottom: 12px;
}

.subtext {
  font-size: 14px;
  color: #666;
}

.right-section {
  padding: 24px;
}

.el-card {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
}

.form-title {
  font-size: 18px;
  font-weight: 500;
  margin-bottom: 20px;
  color: #333;
}

.button-group {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 24px;
}
</style>